/**
 * 地图管理器
 * 提供地图的集中管理和常用操作
 */

import { Map as OlMap } from 'ol';
import { View } from 'ol';
import { fromLonLat, toLonLat, transform } from 'ol/proj';
import { Coordinate } from '../types';

/**
 * 地图管理器类
 */
export class MapManager {
  /**
   * 坐标转换：WGS84 -> Web Mercator (EPSG:3857)
   */
  static lonLatToMercator(coordinate: Coordinate): [number, number] {
    // 确保coordinate是有效的[number, number]类型
    const [lon, lat] = coordinate;
    return fromLonLat([lon, lat]) as [number, number];
  }

  /**
   * 坐标转换：Web Mercator -> WGS84
   */
  static mercatorToLonLat(coordinate: [number, number]): Coordinate {
    return toLonLat(coordinate) as Coordinate;
  }

  /**
   * 计算两点间距离（米）
   */
  static getDistance(coord1: Coordinate, coord2: Coordinate): number {
    const R = 6371000; // 地球半径（米）
    const lat1 = coord1[1] * Math.PI / 180;
    const lat2 = coord2[1] * Math.PI / 180;
    const deltaLat = (coord2[1] - coord1[1]) * Math.PI / 180;
    const deltaLon = (coord2[0] - coord1[0]) * Math.PI / 180;

    const a = Math.sin(deltaLat / 2) * Math.sin(deltaLat / 2) +
              Math.cos(lat1) * Math.cos(lat2) *
              Math.sin(deltaLon / 2) * Math.sin(deltaLon / 2);
    const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));

    return R * c;
  }

  /**
   * 计算多边形面积（平方米）
   */
  static getArea(coordinates: Coordinate[]): number {
    if (coordinates.length < 3) return 0;

    let area = 0;
    const R = 6371000; // 地球半径（米）

    for (let i = 0; i < coordinates.length; i++) {
      const j = (i + 1) % coordinates.length;
      const lat1 = coordinates[i][1] * Math.PI / 180;
      const lon1 = coordinates[i][0] * Math.PI / 180;
      const lat2 = coordinates[j][1] * Math.PI / 180;
      const lon2 = coordinates[j][0] * Math.PI / 180;

      area += (lon2 - lon1) * (2 + Math.sin(lat1) + Math.sin(lat2));
    }

    area = Math.abs(area * R * R / 2);
    return area;
  }

  /**
   * 格式化距离
   */
  static formatDistance(meters: number, unit: 'metric' | 'imperial' = 'metric'): string {
    if (unit === 'imperial') {
      if (meters > 1609.34) {
        return `${(meters / 1609.34).toFixed(2)} mi`;
      } else {
        return `${(meters / 0.3048).toFixed(2)} ft`;
      }
    } else {
      if (meters > 1000) {
        return `${(meters / 1000).toFixed(2)} km`;
      } else {
        return `${meters.toFixed(2)} m`;
      }
    }
  }

  /**
   * 格式化面积
   */
  static formatArea(squareMeters: number, unit: 'metric' | 'imperial' = 'metric'): string {
    if (unit === 'imperial') {
      return `${(squareMeters / 4046.86).toFixed(2)} acres`;
    } else {
      if (squareMeters > 1000000) {
        return `${(squareMeters / 1000000).toFixed(2)} km²`;
      } else {
        return `${squareMeters.toFixed(2)} m²`;
      }
    }
  }
}

